/*!
 * \file test_wt_engine.cpp
 * \project	WonderTrader
 *
 * \author Wesley
 * \date 2025/01/01
 * 
 * \brief WtEngine基类的单元测试
 * 
 * \details 测试WtEngine的核心功能：
 *          - 引擎初始化和配置
 *          - 事件监听器管理
 *          - 风险监控集成
 *          - 数据管理器集成
 *          - 任务调度机制
 *          - 持仓和资金管理
 */
#include <gtest/gtest.h>
#include <gmock/gmock.h>
#include "../../src/WtCore/WtEngine.h"
#include "../../src/WtCore/WtDtMgr.h"
#include "../../src/Share/IniHelper.hpp"
#include "../../src/Includes/WTSContractInfo.hpp"
#include "../../src/Includes/WTSSessionInfo.hpp"
#include "../../src/Includes/WTSVariant.hpp"

using namespace wtp;
using ::testing::_;
using ::testing::Return;
using ::testing::NiceMock;
using ::testing::AtLeast;

/*!
 * \class MockEngineEventListener
 * \brief 模拟引擎事件监听器
 */
class MockEngineEventListener : public IEngineEvtListener {
public:
    MOCK_METHOD(void, on_initialize_event, (), (override));
    MOCK_METHOD(void, on_schedule_event, (uint32_t uDate, uint32_t uTime), (override));
    MOCK_METHOD(void, on_session_event, (uint32_t uDate, bool isBegin), (override));
};

/*!
 * \class MockWtEngine
 * \brief 用于测试的WtEngine模拟类
 * 
 * \details 由于WtEngine是抽象类，需要创建具体实现用于测试
 */
class MockWtEngine : public WtEngine {
public:
    MockWtEngine() : WtEngine("test") {}
    
    // 实现纯虚函数
    virtual void run(bool bAsync = false) override {}
    virtual void init(WTSVariant* cfg, IBaseDataMgr* bdMgr, WtDtMgr* dataMgr, IHotMgr* hotMgr, EventNotifier* notifier) override {
        WtEngine::init(cfg, bdMgr, dataMgr, hotMgr, notifier);
    }
    
    // 暴露protected方法用于测试
    using WtEngine::set_date_time;
    using WtEngine::set_trading_date;
    using WtEngine::addExecuter;
    using WtEngine::addContext;
    using WtEngine::on_init;
    using WtEngine::on_schedule;
    using WtEngine::on_session_begin;
    using WtEngine::on_session_end;
};

/*!
 * \class MockDataManager
 * \brief 模拟数据管理器
 */
class MockDataManager : public WtDtMgr {
public:
    MockDataManager() : WtDtMgr() {}
    MOCK_METHOD(WTSTickData*, grab_last_tick, (const char* code), (override));
};

/*!
 * \class WtEngineTest
 * \brief WtEngine测试套件
 */
class WtEngineTest : public ::testing::Test {
protected:
    void SetUp() override {
        engine = std::make_unique<MockWtEngine>();
        listener = std::make_shared<NiceMock<MockEngineEventListener>>();
        dataMgr = std::make_shared<NiceMock<MockDataManager>>();
        
        // 创建配置
        cfg = WTSVariant::createObject();
        cfg->append("name", "test_engine", false);
        cfg->append("id", "test001", false);
    }
    
    void TearDown() override {
        if (cfg) cfg->release();
    }
    
    std::unique_ptr<MockWtEngine> engine;
    std::shared_ptr<MockEngineEventListener> listener;
    std::shared_ptr<MockDataManager> dataMgr;
    WTSVariant* cfg;
};

/*!
 * \brief 测试引擎基本初始化
 * 
 * \details 验证引擎能够正确初始化和设置基本属性
 */
TEST_F(WtEngineTest, TestBasicInitialization) {
    // 初始化引擎
    engine->init(cfg, nullptr, dataMgr.get(), nullptr, nullptr);
    
    // 验证引擎名称
    EXPECT_EQ(engine->name(), "test");
    
    // 验证引擎状态
    EXPECT_FALSE(engine->isInTrading());
    
    std::cout << "引擎基本初始化测试通过" << std::endl;
}

/*!
 * \brief 测试事件监听器管理
 * 
 * \details 验证事件监听器的注册和事件触发机制
 */
TEST_F(WtEngineTest, TestEventListenerManagement) {
    // 注册事件监听器
    engine->addEventListener(listener.get());
    
    // 初始化引擎
    engine->init(cfg, nullptr, dataMgr.get(), nullptr, nullptr);
    
    // 期望初始化事件被触发
    EXPECT_CALL(*listener, on_initialize_event()).Times(1);
    
    // 触发初始化事件
    engine->on_init();
    
    // 测试调度事件
    uint32_t testDate = 20250101;
    uint32_t testTime = 930;
    
    EXPECT_CALL(*listener, on_schedule_event(testDate, testTime)).Times(1);
    engine->set_date_time(testDate, testTime, 0);
    engine->on_schedule(testDate, testTime, 0);
    
    // 测试交易时段事件
    EXPECT_CALL(*listener, on_session_event(testDate, true)).Times(1);
    engine->on_session_begin(testDate);
    
    EXPECT_CALL(*listener, on_session_event(testDate, false)).Times(1);
    engine->on_session_end(testDate);
    
    std::cout << "事件监听器管理测试通过" << std::endl;
}

/*!
 * \brief 测试日期时间管理
 * 
 * \details 验证引擎的日期时间设置和获取功能
 */
TEST_F(WtEngineTest, TestDateTimeManagement) {
    engine->init(cfg, nullptr, dataMgr.get(), nullptr, nullptr);
    
    // 设置日期时间
    uint32_t testDate = 20250101;
    uint32_t testTime = 93000;
    uint32_t testSecs = 30;
    
    engine->set_date_time(testDate, testTime, testSecs);
    
    // 验证日期时间
    EXPECT_EQ(engine->get_date(), testDate);
    EXPECT_EQ(engine->get_min_time(), testTime);
    EXPECT_EQ(engine->get_secs(), testSecs);
    
    // 设置交易日
    uint32_t tradingDate = 20250102;
    engine->set_trading_date(tradingDate);
    EXPECT_EQ(engine->get_trading_date(), tradingDate);
    
    // 测试交易时间转换
    uint64_t curTime = engine->get_real_time();
    EXPECT_GT(curTime, 0);
    
    std::cout << "日期时间管理测试通过" << std::endl;
}

/*!
 * \brief 测试风险监控集成
 * 
 * \details 验证风险监控器的创建和管理
 */
TEST_F(WtEngineTest, TestRiskMonitorIntegration) {
    // 创建风险监控器包装
    WtRiskMonWrapper* wrapper = new WtRiskMonWrapper(nullptr, nullptr);
    WtRiskMonPtr monPtr = std::make_shared<WtRiskMonWrapper>(nullptr, nullptr);
    
    // 验证智能指针管理
    EXPECT_NE(monPtr, nullptr);
    EXPECT_EQ(monPtr->self(), nullptr); // 因为我们传入的是nullptr
    
    delete wrapper;
    
    std::cout << "风险监控集成测试通过" << std::endl;
}

/*!
 * \brief 测试任务队列机制
 * 
 * \details 验证引擎的异步任务调度功能
 */
TEST_F(WtEngineTest, TestTaskQueueMechanism) {
    engine->init(cfg, nullptr, dataMgr.get(), nullptr, nullptr);
    
    // 创建测试任务
    std::atomic<int> taskCount(0);
    
    auto task1 = [&taskCount]() { taskCount++; };
    auto task2 = [&taskCount]() { taskCount += 2; };
    auto task3 = [&taskCount]() { taskCount += 3; };
    
    // 添加任务到队列
    TaskItem item1 = task1;
    TaskItem item2 = task2;
    TaskItem item3 = task3;
    
    // 验证任务类型
    EXPECT_TRUE(item1 != nullptr);
    EXPECT_TRUE(item2 != nullptr);
    EXPECT_TRUE(item3 != nullptr);
    
    // 执行任务
    item1();
    item2();
    item3();
    
    // 验证任务执行结果
    EXPECT_EQ(taskCount.load(), 6); // 1 + 2 + 3 = 6
    
    std::cout << "任务队列机制测试通过" << std::endl;
}

/*!
 * \brief 测试多监听器支持
 * 
 * \details 验证引擎支持多个事件监听器
 */
TEST_F(WtEngineTest, TestMultipleListeners) {
    auto listener2 = std::make_shared<NiceMock<MockEngineEventListener>>();
    auto listener3 = std::make_shared<NiceMock<MockEngineEventListener>>();
    
    // 注册多个监听器
    engine->addEventListener(listener.get());
    engine->addEventListener(listener2.get());
    engine->addEventListener(listener3.get());
    
    engine->init(cfg, nullptr, dataMgr.get(), nullptr, nullptr);
    
    // 期望所有监听器都收到初始化事件
    EXPECT_CALL(*listener, on_initialize_event()).Times(1);
    EXPECT_CALL(*listener2, on_initialize_event()).Times(1);
    EXPECT_CALL(*listener3, on_initialize_event()).Times(1);
    
    engine->on_init();
    
    std::cout << "多监听器支持测试通过" << std::endl;
}

/*!
 * \brief 测试引擎生命周期
 * 
 * \details 验证引擎的完整生命周期管理
 */
TEST_F(WtEngineTest, TestEngineLifecycle) {
    // 创建和销毁多个引擎实例
    for (int i = 0; i < 5; ++i) {
        auto tempEngine = std::make_unique<MockWtEngine>();
        auto tempCfg = WTSVariant::createObject();
        tempCfg->append("name", "temp_engine", false);
        
        tempEngine->init(tempCfg, nullptr, nullptr, nullptr, nullptr);
        tempEngine->addEventListener(listener.get());
        
        // 模拟引擎运行
        tempEngine->on_init();
        tempEngine->on_session_begin(20250101);
        tempEngine->on_session_end(20250101);
        
        tempCfg->release();
    }
    
    // 如果没有崩溃或内存泄漏，测试通过
    EXPECT_TRUE(true);
    
    std::cout << "引擎生命周期测试通过" << std::endl;
}

/*!
 * \brief 测试错误处理和边界条件
 * 
 * \details 验证引擎在异常情况下的健壮性
 */
TEST_F(WtEngineTest, TestErrorHandlingAndBoundaryConditions) {
    // 测试未初始化状态
    EXPECT_EQ(engine->get_date(), 0);
    EXPECT_EQ(engine->get_trading_date(), 0);
    EXPECT_FALSE(engine->isInTrading());
    
    // 测试空配置初始化
    engine->init(nullptr, nullptr, nullptr, nullptr, nullptr);
    EXPECT_EQ(engine->name(), "test"); // 应该保持构造时的名称
    
    // 测试空监听器
    engine->addEventListener(nullptr); // 不应该崩溃
    engine->on_init(); // 不应该崩溃
    
    // 测试极端日期时间
    engine->set_date_time(99991231, 235959, 59);
    EXPECT_EQ(engine->get_date(), 99991231);
    
    engine->set_date_time(0, 0, 0);
    EXPECT_EQ(engine->get_date(), 0);
    
    std::cout << "错误处理和边界条件测试通过" << std::endl;
}

/*!
 * \brief 测试线程安全性
 * 
 * \details 验证引擎在多线程环境下的安全性
 */
TEST_F(WtEngineTest, TestThreadSafety) {
    engine->init(cfg, nullptr, dataMgr.get(), nullptr, nullptr);
    
    const int NUM_THREADS = 4;
    const int OPERATIONS_PER_THREAD = 100;
    std::vector<std::thread> threads;
    std::atomic<int> successCount(0);
    
    // 多线程并发操作
    for (int i = 0; i < NUM_THREADS; ++i) {
        threads.emplace_back([this, &successCount, i]() {
            for (int j = 0; j < OPERATIONS_PER_THREAD; ++j) {
                // 并发设置日期时间
                uint32_t date = 20250101 + i;
                uint32_t time = 90000 + j;
                engine->set_date_time(date, time, 0);
                
                // 并发获取日期时间
                auto curDate = engine->get_date();
                auto curTime = engine->get_min_time();
                
                // 验证数据有效性
                if (curDate >= 20250101 && curDate <= 20250104 &&
                    curTime >= 90000 && curTime < 100000) {
                    successCount++;
                }
            }
        });
    }
    
    // 等待所有线程完成
    for (auto& t : threads) {
        t.join();
    }
    
    // 验证操作成功率
    int totalOperations = NUM_THREADS * OPERATIONS_PER_THREAD;
    EXPECT_EQ(successCount.load(), totalOperations);
    
    std::cout << "线程安全性测试通过，成功操作: " << successCount << "/" << totalOperations << std::endl;
}

/*!
 * \brief 测试性能特性
 * 
 * \details 验证引擎的性能表现
 */
TEST_F(WtEngineTest, TestPerformanceCharacteristics) {
    engine->init(cfg, nullptr, dataMgr.get(), nullptr, nullptr);
    
    const int NUM_OPERATIONS = 10000;
    
    // 测试日期时间设置性能
    auto start = std::chrono::high_resolution_clock::now();
    
    for (int i = 0; i < NUM_OPERATIONS; ++i) {
        engine->set_date_time(20250101, 93000 + i, i % 60);
        auto date = engine->get_date();
        auto time = engine->get_min_time();
        auto secs = engine->get_secs();
    }
    
    auto end = std::chrono::high_resolution_clock::now();
    auto duration = std::chrono::duration_cast<std::chrono::microseconds>(end - start);
    
    double avgTimeUs = static_cast<double>(duration.count()) / NUM_OPERATIONS;
    
    // 性能基准：平均每次操作应该在1微秒以内
    EXPECT_LT(avgTimeUs, 1.0);
    
    std::cout << "性能特性测试通过，平均操作时间: " << avgTimeUs << " 微秒" << std::endl;
}